package com.wva.user.controller;

import cn.hutool.core.bean.BeanUtil;
import com.wva.common.annotation.authority.Open;
import com.wva.common.context.UserContext;
import com.wva.common.domain.dto.PageQueryDTO;
import com.wva.common.domain.vo.PageQueryVO;
import com.wva.common.domain.vo.UserProfileVO;
import com.wva.common.exception.BusinessException;
import com.wva.common.utils.R;
import com.wva.user.domain.dto.UserFollowDTO;
import com.wva.user.domain.po.User;
import com.wva.user.service.UserFollowService;
import com.wva.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@Api(tags = "用户接口")
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    UserFollowService userFollowService;

    @ApiOperation("关注用户")
    @PostMapping("/follow")
    R<Object> follow(@Validated @RequestBody UserFollowDTO userFollowDTO) {
        Long userId = userFollowDTO.getTargetUserId();
        userFollowService.follow(UserContext.getUserId(), userId);
        return R.ok();
    }

    @ApiOperation("取消关注用户")
    @PostMapping("/cancel-follow")
    R<Object> cancelFollow(@Validated @RequestBody UserFollowDTO userFollowDTO) {
        Long userId = userFollowDTO.getTargetUserId();
        userFollowService.cancelFollow(UserContext.getUserId(), userId);
        return R.ok();
    }

    @Open
    @ApiOperation("分页查询用户的关注者")
    @GetMapping("/{userId}/followers")
    R<PageQueryVO<UserProfileVO>> listFollowers(
            @PathVariable Long userId,
            @Validated PageQueryDTO pageQueryDTO
    ) {
        return R.ok(userFollowService.listFollowers(pageQueryDTO, userId));
    }

    @Open
    @ApiOperation("分页查询用户的关注的用户")
    @GetMapping("/{userId}/followings")
    R<PageQueryVO<UserProfileVO>> listFollowings(
            @PathVariable Long userId,
            @Validated PageQueryDTO pageQueryDTO
    ) {
        return R.ok(userFollowService.listFollowings(pageQueryDTO, userId));
    }

    @Open
    @ApiOperation("获取用户基本信息")
    @GetMapping("/{userId}/profile")
    R<UserProfileVO> getBaseInfo(@PathVariable Long userId) {
        User user = userService.getById(userId);
        if (user == null) throw new BusinessException("用户不存在");
        UserProfileVO userProfileVO = BeanUtil.copyProperties(user, UserProfileVO.class);

        //是否关注了此用户
        userProfileVO.setFollow(
                userFollowService.isFollow(UserContext.getUserId(), userId)
        );

        //粉丝数量
        userProfileVO.setFansCount(
                userFollowService.getFollowerCountByUserId(userId)
        );

        return R.ok(userProfileVO);
    }
}
